
import { Input, Segmented, Button, Select, DatePicker, Flex } from '@/components/base';
import { PageFilter } from '@/components/page-filter';
import styles from './index.module.less';
import { AdvancedTable } from '@/components/advanced-table';
import { useNavigate } from 'react-router-dom';
import * as hooks from './hooks';
import * as apis from '@/apis';
import { useLoading, usePagination, useSearch } from '@/tools/hooks';
import React from 'react';
import dayjs from 'dayjs';
import SelectUser from '@/components/select-user';
import { SelectClient } from '@/components/select-client';
import { RangeNumber } from '@/components/range-number';
import { useSorter } from '@/tools/hooks/use-sorter';
import * as capability from './capability';

const { RangePicker } = DatePicker;

/** 订单列表 */
export function OrderTable() {
    const navigate = useNavigate();
    const { setSearchData, searchData } = useSearch('order_search');
    const { setSorterData, sorterData } = useSorter('order_sorter');
    const { orderStatus, setOrderStatus } = hooks.useOrderStatus();
    const { setPagination, page, pageSize } = usePagination();
    const [dataSource, setDataSource] = React.useState([]);
    const [total, setTotal] = React.useState(0);
    const { run, loading } = useLoading();

    const refresh = React.useCallback(async () => {
        await run(async () => {
            try {
                const pagination = { current: page, pageSize };
                const sorter = sorterData;
                const data = await apis.order.list.post({ pagination, sorter, orderStatus, ...searchData });
                setDataSource(data.list);
                setTotal(data.pagination.total);
            } catch (error) {
                console.error(error);
                setDataSource([]);
                setTotal(0);
            }
        });
    }, [run, page, pageSize, sorterData, orderStatus, searchData]);

    React.useEffect(() => {
        refresh();
    }, [refresh]);

    return (
        <div>
            <PageFilter
                formFlex={80}
                searchData={searchData}
                onSearch={e => {
                    setPagination({ current: 1, pageSize });
                    setSearchData(e);
                }}
                items={[
                    {
                        label: '订单号',
                        name: 'orderNo',
                        children: <Input />
                    }, {
                        label: '公司',
                        name: 'company',
                        children: <Select allowClear style={{ width: '100%' }} options={[{ label: "火猴", value: 'hh' }, { label: "悦逗蛙", value: 'ydw' }]} />
                    }, {
                        label: '商务',
                        name: 'commercialSpecialist',
                        children: <SelectUser />
                    }, {
                        label: 'PM',
                        name: 'pm',
                        children: <SelectUser />
                    }, {
                        label: "接单时间",
                        name: "orderTime",
                        ...filterFromItemTime,
                        children: <RangePicker style={{ width: '100%' }} />
                    }, {
                        label: '客户名称',
                        name: 'clientId',
                        children: <SelectClient />
                    }, {
                        label: '项目名称',
                        name: 'project',
                        children: <Input />
                    }, {
                        label: '合作模式',
                        name: 'cooperationMode',
                        children: <Input />
                    }, {
                        label: '承接类型',
                        name: 'undertakingType',
                        children: <Input />
                    }, {
                        label: '计划开始时间',
                        name: 'planStartTime',
                        ...filterFromItemTime,
                        children: <RangePicker style={{ width: '100%' }} />
                    }, {
                        label: '实际开始时间',
                        name: 'startTime',
                        ...filterFromItemTime,
                        children: <RangePicker style={{ width: '100%' }} />
                    }, {
                        label: '商务计划完成时间',
                        name: 'scheduledCompletionTime',
                        ...filterFromItemTime,
                        children: <RangePicker style={{ width: '100%' }} />
                    }, {
                        label: '制作计划完成时间',
                        name: 'produceCompletionTime',
                        ...filterFromItemTime,
                        children: <RangePicker style={{ width: '100%' }} />
                    }, {
                        label: '实际完成时间',
                        name: 'completionTime',
                        ...filterFromItemTime,
                        children: <RangePicker style={{ width: '100%' }} />
                    }, {
                        label: '单价',
                        name: 'price',
                        children: <RangeNumber />
                    }, {
                        label: '制作人天',
                        name: 'personDays',
                        children: <RangeNumber />
                    }, {
                        label: '商务人天',
                        name: 'businessDay',
                        children: <RangeNumber />
                    }, {
                        label: '总金额（元）',
                        name: 'amount',
                        children: <RangeNumber />
                    }, {
                        label: '付款周期（天）',
                        name: 'paymentCycle',
                        children: <RangeNumber />
                    }, {
                        label: '结算周期（天）',
                        name: 'billingCycle',
                        children: <RangeNumber />
                    }
                ]}
            />
            <div className={styles['ability']} >
                <Button type='primary' onClick={() => { navigate('../create') }} >创建订单</Button>
            </div>
            <div className={styles['state']} >
                <Segmented
                    value={orderStatus}
                    options={Array.from(apis.order.OrderStatusMap.keys()).map(e => ({ label: apis.order.OrderStatusMap.get(e), value: e }))}
                    onChange={e => {
                        setPagination({ current: 1, pageSize });
                        setOrderStatus(e)
                    }}
                />
            </div>
            <AdvancedTable
                size='small'
                loading={loading}
                scroll={{ x: '100%' }}
                dataSource={dataSource}
                columns={[
                    {
                        title: '订单号',
                        dataIndex: 'orderNo',
                        key: 'orderNo',
                        width: 200
                    },
                    {
                        title: '公司',
                        dataIndex: 'company',
                        key: 'company',
                        width: 200
                    },
                    {
                        title: '商务',
                        dataIndex: 'commercialSpecialistName',
                        key: 'commercialSpecialistName',
                        width: 100
                    },
                    {
                        title: 'PM',
                        dataIndex: 'pmName',
                        key: 'pmName',
                        width: 100
                    },
                    {
                        title: "接单时间",
                        dataIndex: 'orderTime',
                        key: 'orderTime',
                        width: 120,
                        align: 'center',
                        sorter: true,
                        render: (v) => v ? dayjs(v).format('YYYY-MM-DD') : ''
                    },
                    {
                        title: '归属部门',
                        dataIndex: 'deptName',
                        key: 'deptName',
                        width: 200
                    },
                    {
                        title: '客户名称',
                        dataIndex: 'clientName',
                        key: 'clientName',
                        width: 200
                    },
                    {
                        title: '项目名称',
                        dataIndex: 'project',
                        key: 'project',
                        width: 200
                    },
                    {
                        title: '合作模式',
                        dataIndex: 'cooperationMode',
                        key: 'cooperationMode',
                        width: 100
                    },
                    {
                        title: '承接类型',
                        dataIndex: 'undertakingType',
                        key: 'undertakingType',
                        width: 120
                    },
                    {
                        title: '计划开始时间',
                        dataIndex: 'planStartTime',
                        key: 'planStartTime',
                        width: 120,
                        align: 'center',
                        sorter: true,
                        render: (v) => v ? dayjs(v).format('YYYY-MM-DD') : ''
                    },
                    {
                        title: '实际开始时间',
                        dataIndex: 'startTime',
                        key: 'startTime',
                        width: 120,
                        align: 'center',
                        sorter: true,
                        render: (v) => v ? dayjs(v).format('YYYY-MM-DD') : ''
                    },
                    {
                        title: '商务计划完成时间',
                        dataIndex: 'scheduledCompletionTime',
                        key: 'scheduledCompletionTime',
                        width: 140,
                        align: 'center',
                        sorter: true,
                        render: (v) => v ? dayjs(v).format('YYYY-MM-DD') : ''
                    },
                    {
                        title: '制作计划完成时间',
                        dataIndex: 'produceCompletionTime',
                        key: 'produceCompletionTime',
                        width: 140,
                        align: 'center',
                        sorter: true,
                        render: (v) => v ? dayjs(v).format('YYYY-MM-DD') : ''
                    },
                    {
                        title: '实际完成时间',
                        dataIndex: 'completionTime',
                        key: 'completionTime',
                        width: 140,
                        align: 'center',
                        sorter: true,
                        render: (v) => v ? dayjs(v).format('YYYY-MM-DD') : ''
                    },
                    {
                        title: '单价',
                        dataIndex: 'price',
                        key: 'price',
                        width: 120,
                        align: 'right',
                        sorter: true,
                        render: moneyFormatter,
                    },
                    {
                        title: '制作人天',
                        dataIndex: 'personDays',
                        key: 'personDays',
                        width: 100,
                        align: 'right',
                        sorter: true,
                    },
                    {
                        title: '商务人天',
                        dataIndex: 'businessDay',
                        key: 'businessDay',
                        width: 100,
                        align: 'right',
                        sorter: true,
                    },
                    {
                        title: '总金额（元）',
                        dataIndex: 'amount',
                        key: 'amount',
                        width: 120,
                        align: 'right',
                        render: moneyFormatter,
                        sorter: true,
                    },
                    {
                        title: '付款周期（天）',
                        dataIndex: 'paymentCycle',
                        key: 'paymentCycle',
                        width: 120,
                        align: 'right',
                        sorter: true,
                    },
                    {
                        title: '结算周期（天）',
                        dataIndex: 'billingCycle',
                        key: 'billingCycle',
                        width: 120,
                        align: 'right',
                        sorter: true,
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 140,
                        render: (_, record, index) => (
                            <Flex className={styles['action']} >
                                <capability.View record={record} index={index} />
                                <capability.Edit record={record} index={index} />
                                <capability.Approval record={record} index={index} />
                                <capability.InitiateApproval record={record} refresh={refresh} index={index} />
                            </Flex>
                        ),
                    }
                ]}
                onChange={(pagination, _, sorter) => {
                    setPagination(pagination);
                    if (Array.isArray(sorter)) { sorter = sorter[0] }
                    setSorterData({
                        columnKey: sorter?.column?.dataIndex?.toString(),
                        order: sorter?.order,
                    })

                }}
                pagination={{
                    total,
                    current: page,
                    pageSize: pageSize,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: total => `共 ${total} 条`,
                }}
            />
        </div>
    )
}

/** 金钱格式化，保留两位小数（¥100,000.00） */
function moneyFormatter(value: string | number) {
    return `¥${Number(value).toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')}`;
}

const filterFromItemTime = {
    getValueProps: (value: any) => {
        if (Array.isArray(value)) {
            return { value: value.map(e => dayjs(e)) }
        }
        return { value: undefined }
    },
    normalize: (value: any) => {
        if (Array.isArray(value)) {
            return value.map(e => dayjs.isDayjs(e) ? e.format('YYYY-MM-DD') : undefined)
        }
        return undefined;
    },
}